﻿using Essensoft.Paylink.Alipay;
using Essensoft.Paylink.Alipay.Notify;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using B.S.Medical.Api.Write.Application.Command.Pay;
using MediatR;
using System.Text.Json;

namespace B.S.Medical.Api.Write.Controllers.Pay
{
    [Route("api/[controller]")]
    [ApiController]
    public class AlipayNotifyController : ControllerBase
    {
        private readonly ILogger<AlipayNotifyController> _logger;
        private readonly IAlipayNotifyClient _client;
        private readonly IOptions<AlipayOptions> _optionsAccessor;
        private readonly IMediator _mediator;

        public AlipayNotifyController(
            ILogger<AlipayNotifyController> logger, 
            IAlipayNotifyClient client, 
            IOptions<AlipayOptions> optionsAccessor,
            IMediator mediator)
        {
            _logger = logger;
            _client = client;
            _optionsAccessor = optionsAccessor;
            _mediator = mediator;
        }

        /// <summary>
        /// 手机网站支付异步通知
        /// </summary>
        [Route("wappay")]
        [HttpPost]
        public async Task<IActionResult> WapPay()
        {
            try
            {
                var notify = await _client.CertificateExecuteAsync<AlipayTradeWapPayNotify>(Request, _optionsAccessor.Value);
                switch (notify.TradeStatus)
                {
                    case AlipayTradeStatus.Success: // 支付成功
                        _logger.LogInformation("手机网站支付异步通知-交易支付成功 => OutTradeNo: " + notify.OutTradeNo);
                        //修改订单状态
                        var updateCommand = new UpdatePaymentStatusCommand
                        {
                            OrderNo = notify.OutTradeNo,
                            TradeNo = notify.TradeNo,
                            PayStatus = "已支付",
                            IsPaid = true,
                            PayTime = DateTime.Parse(notify.GmtPayment),
                            PayType = "支付宝",
                            PayChannel = "手机网站支付",
                            NotifyRaw = JsonSerializer.Serialize(notify)
                        };
                        await _mediator.Send(updateCommand);

                        return AlipayNotifyResult.Success;
                    case AlipayTradeStatus.Closed: // 交易关闭
                        _logger.LogInformation("手机网站支付异步通知-未付款交易超时关闭，或支付完成后全额退款 => OutTradeNo: " + notify.OutTradeNo);
                        // 更新订单状态为关闭
                        var closeCommand = new UpdatePaymentStatusCommand
                        {
                            OrderNo = notify.OutTradeNo,
                            TradeNo = notify.TradeNo,
                            PayStatus = "TRADE_CLOSED",
                            IsPaid = false,
                            PayTime = null,
                            PayType = "支付宝",
                            PayChannel = "手机网站支付",
                            NotifyRaw = JsonSerializer.Serialize(notify)
                        };
                        await _mediator.Send(closeCommand);
                        
                        return AlipayNotifyResult.Success;
                    case AlipayTradeStatus.Finished: // 交易完结
                        _logger.LogInformation("手机网站支付异步通知-交易结束，不可退款 => OutTradeNo: " + notify.OutTradeNo);
                        // 更新订单状态为完结
                        var finishCommand = new UpdatePaymentStatusCommand
                        {
                            OrderNo = notify.OutTradeNo,
                            TradeNo = notify.TradeNo,
                            PayStatus = "TRADE_FINISHED",
                            IsPaid = true,
                            PayTime = DateTime.Parse(notify.GmtPayment),
                            PayType = "支付宝",
                            PayChannel = "手机网站支付",
                            NotifyRaw = JsonSerializer.Serialize(notify)
                        };
                        await _mediator.Send(finishCommand);
                        
                        return AlipayNotifyResult.Success;
                    default:
                        return AlipayNotifyResult.Failure;
                }
            }
            catch (AlipayException ex)
            {
                _logger.LogWarning("出现异常: " + ex.Message);
                return AlipayNotifyResult.Failure;
            }
        }
    }
}
